﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Input;
using SocialKit.LightRest;

namespace LightRestDemos
{
    public partial class MainWindow : Window
    {
        RestClient client;

        public MainWindow()
        {
            InitializeComponent();

            this.client = new RestClient();
            this.client.SendAsyncCompleted += client_SendAsyncCompleted;

            //var consumer = new Consumer
            //{
            //    Key = "k",
            //    Secret = "s",
            //    RequestTokenUri = "http://host/oauth/request_token",
            //    AuthorizeUri = "http://host/oauth/authorize",
            //    AccessTokenUri = "http://host/oauth/access_token"
            //};

            //var requestToken = consumer.GetRequestToken();
            //var authorizeUri = requestToken.GetNormalizedAuthorizeUri();
            ////Redirect to the authorize uri to allow user authorize.

            ////Then use the oauth_verifier to retrieve the access token.
            //var accessToken = requestToken.ToAccessToken("v");

            ////save the access token for later uses :)
        }

        void client_SendAsyncCompleted(object sender, SendAsyncCompletedEventArgs e)
        {
            this.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal, (Action)(() =>
            {
                this.sendButton.IsEnabled = true;
                this.responsePanel.IsEnabled = true;
                this.responsePanel.SelectedIndex = 0;
                this.responseBodyTab.Header = "body";

                try
                {
                    if (e.Error != null)
                    {
                        this.responseStatusOrExceptionMessage.Text = "Error: " + FindMessage(e.Error);
                        this.responseHeadersOrException.Text = e.Error.ToString();

                        if (e.Response != null)
                        {
                            this.responseBody.Text = e.Response.ReadContentAsString();
                        }

                        return;
                    }

                    this.responseStatusOrExceptionMessage.Text = "Response: " + (int)e.Response.StatusCode + " " + e.Response.StatusCode;
                    this.responseMethodAndUri.Text = e.Response.Method + " " + e.Response.ResponseUri;
                    this.responseHeadersOrException.Text = e.Response.Headers.ToString();

                    if (!string.IsNullOrEmpty(e.Response.ContentType))
                    {
                        responseBodyTab.Header = "body (" + e.Response.ContentType + ")";
                    }

                    if (e.Response.ContentType.ToLower().IndexOf("xml") != -1)
                    {
                        var xml = e.Response.ReadContentAsXElement();

                        this.responseBody.Text = xml == null ? "(empty)" : xml.ToString();
                    }
                    else if (e.Response.ContentType.ToLower().IndexOf("text") != -1)
                    {
                        this.responseBody.Text = e.Response.ReadContentAsString();
                    }
                    else
                    {
                        this.responseBody.Text = e.Response.ToString();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }));
        }

        int currentRequest = 0;

        private void sendButton_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var uri = requestUri.Text;

                if (!requestUri.Items.Contains(uri))
                {
                    requestUri.Items.Add(uri);
                }

                var request = new HttpRequestMessage(requestMethod.Text, new Uri(uri, UriKind.Absolute));

                if (checkRequestBody.IsChecked ?? false)
                {
                    request.SetContent(EmptyContent.Parse(requestBody.Text));
                }

                currentRequest++;
                object userState = currentRequest;

                sendButton.IsEnabled = false;
                responsePanel.IsEnabled = false;
                this.responseBody.Text = "";
                this.responseHeadersOrException.Text = "";
                this.responseMethodAndUri.Text = "";
                this.responseStatusOrExceptionMessage.Text = "";
                this.responseTab.Header = "response #" + userState;

                client.SendAsync(request, userState);
            }
            catch (Exception ex)
            {
                responsePanel.IsEnabled = true;
                this.sendButton.IsEnabled = true;
                responseStatusOrExceptionMessage.Text = "Error on send: " + FindMessage(ex);
                responseHeadersOrException.Text = ex.ToString();
            }
        }

        static string FindMessage(Exception exception)
        {
            if (!string.IsNullOrEmpty(exception.Message) || exception.InnerException == null)
            {
                return exception.Message;
            }

            return FindMessage(exception.InnerException);
        }

        private void clearRequestBody(object sender, RoutedEventArgs e)
        {
            requestBody.Text = "";
        }

        private void sendOnEnter(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                sendButton_Click(this, e);
            }
        }
    }
}